import $ from 'jquery';
import { Entity,Entities,DBAccess} from './Gener.js';
//import {GenerBindDDL,GetLocalWFPreHref} from './tools.js';
// 用来存放调用此js的vue组件实例（this）
let vm = null
const sendThis = ( _this )=> {
    vm = _this
}
/**
 * 获取文本字段的小范围多选或者单选的数据
 * @param {any} mapExt
 * @param {any} frmData
 * @param {any} defVal
 */
function GetDataTableOfTBChoice(mapExt, frmData,webUser) {
    let data = [];
    switch (parseInt(mapExt.DoWay)) {
        case 1:
            var tag1 = mapExt.Tag1;
            tag1 = tag1.replace(/;/g, ',');
            $.each(tag1.split(","), function (i, o) {
                data.push({
                    No: i+'',
                    Name: o,
                })
            });
            break;
        case 2: //枚举.
            var enums=[];
            if (frmData != null && frmData != undefined) {
                data = frmData[mapExt.AttrOfOper];
                if (data == undefined)
                    data = frmData[mapExt.Tag2];
                if (data == undefined) {
                    enums = frmData.Sys_Enum;
                    enums = $.grep(enums, function (value) {
                        return value.EnumKey == mapExt.Tag2;
                    });
                    $.each(enums, function (i, o) {
                        data.push({
                            No: o.IntKey+'',
                            Name: o.Lab,
                        })
                    });
                }
            } else {
                enums = new Entities("BP.Sys.SysEnums");
                enums.Retrieve("EnumKey", mapExt.Tag2);

                $.each(enums, function (i, o) {
                    data.push({
                        No: o.IntKey+'',
                        Name: o.Lab,
                    })
                });
            }

            break;
        case 3: //外键表.
            var dt=[];
            var en=[];
            if (frmData != null && frmData != undefined) {

                dt = frmData[mapExt.Tag3];
                if (dt == undefined) {
                    en = new Entity("BP.Sys.SFTable", mapExt.Tag3);
                    dt = en.DoMethodReturnJSON("GenerDataOfJson");
                    if (dt.length > 400) {
                        vm.$alert("数据量太大，请检查配置是否有逻辑问题，或者您可以使用搜索多选或者pop弹出窗选择:" + mapExt.Tag3);
                        return null;
                    }

                    frmData[mapExt.Tag3] = dt;
                    data = [];
                    dt.forEach(function (item) {
                        data.push({
                            No: item.No,
                            Name: item.Name,

                        })
                    })
                }
            } else {
                en = new Entity("BP.Sys.SFTable", mapExt.Tag3);
                dt = en.DoMethodReturnJSON("GenerDataOfJson");

                if (dt.length > 400) {
                    vm.$alert("数据量太大，请检查配置是否有逻辑问题，或者您可以使用搜索多选或者pop弹出窗选择:" + mapExt.Tag3);
                    return null;
                }
                data = [];
                dt.forEach(function (item) {
                    data.push({
                        No: item.No,
                        Name: item.Name,

                    })
                })
            }
            break;
        case 4:
            var tag4SQL = mapExt.Tag4;

            tag4SQL = DealExp(tag4SQL);
            if (tag4SQL.indexOf('@') == 0) {
                vm.alert('约定的变量错误:' + tag4SQL + ", 没有替换下来.");
                return null;
            }
            tag4SQL = tag4SQL.replace(/~/g, "'");

            var dtt = DBAccess.RunSQLReturnTable(tag4SQL);
            if (dtt.length > 400) {
                vm.$alert("数据量太大，请检查配置是否有逻辑问题，或者您可以使用搜索多选或者pop弹出窗选择:" + mapExt.Tag3);
                return null;
            }
            data = [];
            dtt.forEach(function (item) {
                data.push({
                    No: item.No,
                    Name: item.Name,

                })
            })
            break;
        default:
            vm.$alert("未判断的模式");
            return null;
    }
    return data;

}


/**
 * 获取数据的方法
 * @param {any} dbSrc 请求数据集合的内容
 * @param {any} dbType 请求数据的集合了类型 SQL,函数,URL
 * @param {any} dbSource 如果是SQL的时，SQL的查询来源，本地，外部数据源
 * @param {any} keyVal 选择替换的值
 */
function GetDataTableByDB(dbSrc, dbType, dbSource, keyVal) {
    if (dbSrc == null || dbSrc == undefined || dbSrc == "")
        return null;
    //处理sql，url参数.
    dbSrc = dbSrc.replace(/~/g, "'");
    if (keyVal != null) {
        if (dbType == 0)
            keyVal = keyVal.replace(/'/g, '');

        dbSrc = dbSrc.replace(/@Key/g, keyVal);
        dbSrc = dbSrc.replace(/@key/g, keyVal);
        dbSrc = dbSrc.replace(/@KEY/g, keyVal);
    }
    dbSrc = DealExp(dbSrc);
    //获取数据源.
    let dataObj = DBAccess.RunDBSrc(dbSrc, dbType, dbSource);
    return dataObj;
}

function GetCommPopData(mapExt,popModel){
    let data = [];
    //获取实体信息
    let ens = [];

    if (popModel == "PopBindEnum") {
        ens = new Entities("BP.Sys.SysEnums");
        ens.Retrieve("EnumKey", mapExt.Tag2);
        $.each(ens, function (i, item) {
            data.push({
                No: item.IntKey+'',
                Name: item.Lab,
            })
        })
        return data;
    }
    if (popModel == "PopBindSFTable") {
        let en = new Entity("BP.Sys.SFTable", mapExt.Tag2);
        ens = en.DoMethodReturnJSON("GenerDataOfJson");
        return ens;
    }
    if (popModel == "PopTableList") {
        ens = GetDataTableByDB(mapExt.Tag2, mapExt.DBType, mapExt.FK_DBSrc, null);
        return ens;
    }
    if (popModel == "PopGroupList") {
        ens = GetDataTableByDB(mapExt.Tag2, mapExt.DBType, mapExt.FK_DBSrc, null);
        //获取分组信息
        let groups = GetDataTableByDB(mapExt.Tag1, mapExt.DBType, mapExt.FK_DBSrc);
        let myidx = 0;
        let oOfEn = "";
        for (let obj in ens[0]) {
            if (myidx == 2) {
                oOfEn = obj;
                break;
            }
            myidx++;
        }

        myidx = 0;
        let oOfGroup;
        for (let obj in groups[0]) {
            if (myidx == 0) {
                oOfGroup = obj;
                break;
            }
            myidx++;
        }
        groups.forEach(function (group) {
            let options = [];
            $.each(ens, function (i,item) {
                if (item[oOfEn] == group[oOfGroup]) {
                    options.push({
                        No: item.No,
                        Name: item.Name,
                    })
                }
            });

            data.push({
                Name: group.Name,
                No: group[oOfGroup],
                options: options,
            })
        })
    }
    return data;
}

function GetFrmEleDBsByKeyOfEn(keyOfEn,fk_mapData,refPKVal){
    let ens = new Entities("BP.Sys.FrmEleDBs");
    ens.Retrieve("FK_MapData",fk_mapData, "EleID", keyOfEn, "RefPKVal", refPKVal);
    if(ens.length==0)
        return [];
    let options=[];
    ens = ens.GetEns();
    ens.data.forEach(en=>{
        options.push({
            No:en.Tag1,
            Name:en.Tag2
        })
    })
    return options;
}

function ReqDays(mapExt,mainData,_this){
    let startDt = mapExt.Tag1;//开始日期
    let endDt = mapExt.Tag2;//结束日期
    let type = mapExt.Tag3;//是否包含节假日 0包含，1不包含
    let dateSpan;
    startDt = Date.parse(mainData[startDt]);
    endDt = Date.parse(mainData[endDt]);
    dateSpan = endDt - startDt;
    if(Object.is(dateSpan, NaN)){
        return "";
    }

    if(dateSpan<0){
        _this.$message.warning("结束时间不能小于开始时间");
        return "";
    }
    dateSpan = Math.abs(dateSpan);
    dateSpan = Math.floor(dateSpan / (24 * 3600 * 1000));
    if(type == 0){ //包含节假日
        let holidayEn = new _this.Entity("BP.Sys.GloVar");
        holidayEn.No = "Holiday";
        if (holidayEn.RetrieveFromDBSources() == 1) {
            let holidays = holidayEn.Val.split(",");
            dateSpan = dateSpan - (holidays.length - 1);
            //检查计算的天数
            if (dateSpan <= 0) {
                _this.$message.warning("请假时间内均为节假日");
                dateSpan = "";
            }
        }
    }
    return dateSpan;
}
/**
 *
 * 表达式的替换
 * @param expStr
 * @returns {*}
 * @constructor
 */
function DealExp(expStr,_this) {
    if(_this==undefined)
        _this = vm;
    let webUser =  _this.$store.getters.getWebUser;
    if (expStr.indexOf('@') == -1)
        return expStr;

    //替换表达式常用的用户信息
    expStr = expStr.replace('@WebUser.No', webUser.No);
    expStr = expStr.replace('@WebUser.Name', webUser.Name);
    expStr = expStr.replace("@WebUser.FK_DeptNameOfFull", webUser.FK_DeptNameOfFull);
    expStr = expStr.replace('@WebUser.FK_DeptName', webUser.FK_DeptName);
    expStr = expStr.replace('@WebUser.FK_Dept', webUser.FK_Dept);
    if (expStr.indexOf('@') == -1)
        return expStr;
    let mainData = _this.mainData;
    if(mainData==null || mainData==undefined){
        _this.$alert("表达式."+expStr+"含有@符号还没有被替换，请联系开发人员协作检查出错原因");
        return expStr;
    }
    for(var key in mainData){
        expStr = expStr.replace("@" + key, mainData[key]);
        if (expStr.indexOf('@') == -1)
            return expStr;
    }
    return expStr;
}

/**
 * 填充其他控件
 * @param selectVal 选中的值
 * @param refPK mapExt关联的主键
 * @param elementId 元素ID
 */
function FullIt(selectVal,mapExt,mapAttr) {
    let oid = vm.params.OID
    if (oid == null || oid==undefined)
        oid =vm.params.WorkID;

    if (oid == null || oid == undefined)
        oid =vm.params.RefPKVal;

    if (oid == null || oid == undefined) {
        oid = 0;
        return;
    }

    //执行确定后执行的JS
    let backFunc = mapExt.Tag5;
    if (backFunc != null && backFunc != "" && backFunc != undefined){
        backFunc = backFunc.replace(/@Key/g, selectVal);
        backFunc = backFunc.replace(/@key/g, selectVal);
        backFunc = backFunc.replace(/@KEY/g, selectVal);
        backFunc = DealExp(backFunc);
        DBAccess.RunFunctionReturnStr(backFunc);
    }

    if(mapExt.MyPK.indexOf("FullData")==-1){
        let mapExts = vm.frmData.Sys_MapExts;
        mapExts=mapExts.filter(function (item) {
            return item.MyPK == mapExt.MyPK + "_FullData";
        });
        //没有填充其他控件
        if(mapExts.length==0)
            return ;
        mapExt = mapExts[0];
    }

    //执行填充主表的控件.
    FullCtrl(selectVal,mapExt);

    //执行个性化填充下拉框，比如填充ddl下拉框的范围.
    FullCtrlDDL(selectVal, mapExt);

    //执行填充从表.
    FullDtl(selectVal, mapExt,oid);

    //执行确定后执行的JS
    backFunc = mapExt.Tag2;
    if (backFunc != null && backFunc != "" && backFunc != undefined){
        backFunc = backFunc.replace(/@Key/g, selectVal);
        backFunc = backFunc.replace(/@key/g, selectVal);
        backFunc = backFunc.replace(/@KEY/g, selectVal);
        backFunc = DealExp(backFunc);
        DBAccess.RunFunctionReturnStr(backFunc);
    }

}

function FullCtrl(){

}
function FullCtrlDDL(){

}
function FullDtl(){

}
function FormatDate(date, mask) {
    let d = date;
    let zeroize = function (value, length) {
        if (!length) length = 2;
        value = String(value);
        for (var i = 0, zeros = ''; i < (length - value.length); i++) {
            zeros += '0';
        }
        return zeros + value;
    }

    return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0) {
        switch ($0) {
            case 'd': return d.getDate();
            case 'dd': return zeroize(d.getDate());
            case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
            case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
            case 'M': return d.getMonth() + 1;
            case 'MM': return zeroize(d.getMonth() + 1);
            case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
            case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
            case 'yy': return String(d.getFullYear()).substr(2);
            case 'yyyy': return d.getFullYear();
            case 'h': return d.getHours() % 12 || 12;
            case 'hh': return zeroize(d.getHours() % 12 || 12);
            case 'H': return d.getHours();
            case 'HH': return zeroize(d.getHours());
            case 'm': return d.getMinutes();
            case 'mm': return zeroize(d.getMinutes());
            case 's': return d.getSeconds();
            case 'ss': return zeroize(d.getSeconds());
            case 'l': return zeroize(d.getMilliseconds(), 3);
            case 'L': var m = d.getMilliseconds();
                if (m > 99) m = Math.round(m / 10);
                return zeroize(m);
            case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
            case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
            case 'Z': return d.toUTCString().match(/[A-Z]+$/);
            // Return quoted strings with the surrounding quotes removed
            default: return $0.substr(1, $0.length - 2);
        }
    });
}

export{
    sendThis,
    DealExp,
    GetDataTableOfTBChoice,
    GetDataTableByDB,
    GetCommPopData,
    FullIt,
    FormatDate,
    GetFrmEleDBsByKeyOfEn,
    ReqDays
}


